
package com.ymk.base.utlis;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * This sample demonstrates how to create an empty folder under
 * specfied bucket to Aliyun OSS using the OSS SDK for Java.
 */
@Component
public class OSSCreateFolder {

    private final static Logger logger = LoggerFactory.getLogger(OSSCreateFolder.class);

    @Value("${AccessKeyID}")
    private String ACCESS_KEY_ID;
    @Value("${AccessKeySecret}")
    private String ACCESS_KEY_SECRET;


    private final static String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private final static String RETURN_URL = "https://bsbang."+ENDPOINT+"/";
    private final static String BUCKET_NAME = "bsbang";

    public String upload(String name,String contentType, byte[] message) {
        String re = null;
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        String fileName = this.getName(contentType)+name;
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(contentType);

            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME,  fileName, new ByteArrayInputStream(message),objectMetadata);
            ossClient.putObject(putObjectRequest);
            re = RETURN_URL + fileName;
        } catch (OSSException | ClientException oe) {
            logger.error(oe.toString());
        } finally {
            ossClient.shutdown();
        }
        return re;
    }

    private String getName(String name){
        if (name.contains("mp4")){
            return "video/";
        }
        if (name.contains("image")){
            return "image/";
        }
        if (name.contains("zip")){
            return "file/";
        }
        return "";
    }
}